//引入express
const express = require('express')
//引入router
const router = express.Router()
//引入Schema
const User = require('../models/Users')
//引入RoleSchema
const Role = require('../models/Roles')
//引入md5，加密密码
//const md5 = require('md5')
//引入bcrypt
const bcrypt = require('bcrypt')
//引入gravatar
const gravatar = require('gravatar');
//引入jsonwebToken
const jwt = require('jsonwebtoken')
//引入passport，配合possport-JWT完成对token的验证
const passport = require('passport')

router.get('/test', (req, res) => {
  res.json('hello')
})

//注册接口
router.post('/register', (req, res) => {
  const registerData = req.body
  User.findOne({ email: registerData.email })
    .then(user => {
      if (user) {
        return res.json({
          status: 400,
          msg: '用户已存在'
        })
      } else {
        const avatar = gravatar.url(req.body.email, { s: '200', r: 'pg', d: 'mm' });
        const newUser = new User({
          username: registerData.username,
          email: registerData.email,
          password: registerData.password,
          phone: registerData.phone,
          job: registerData.job,
          phone: registerData.phone,
          avatar: avatar
        })
        bcrypt.genSalt(10, function (err, salt) {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err
            newUser.password = hash
            newUser.save()
              .then(user => {
                res.json({
                  status: 200,
                  data: user,
                  msg: '注册成功'
                })
              })
              .catch(err => {
                res.json(err)
              })
          });
        });
      }
    })
})

//登录接口
router.post('/login', (req, res) => {
  const loginData = req.body
  User.findOne({ email: loginData.email })
    .then(user => {
      if (!user) { //如果没有这个用户
        return res.json({
          status: 400,
          msg: '该用户不存在'
        })
      } else {
        //如果用户存在，检查加密后的密码是否与之匹配
        bcrypt.compare(loginData.password, user.password)
          .then(isMatch => {
            if (isMatch) {
              if (user.role_id) {
                Role.findOne({ _id: user.role_id })
                  .then(role => {
                    user._doc.role = role
                    console.log('role user', user)
                    const rule = {
                      id: user.id,
                      username: user.username,
                      email: user.email,
                      avatar: user.avatar,
                      phone: user.phone,
                      job: user.job,
                      role_id: user.role_id,
                      role: user._doc.role
                    }
                    //进行token的设置
                    jwt.sign(rule, 'secret', { expiresIn: 3600 }, (err, token) => {
                      if (err) throw err
                      res.json({
                        status: 200,
                        msg: '登录成功',
                        data: {
                          id: user.id,
                          username: user.username,
                          email: user.email,
                          avatar: user.avatar,
                          phone: user.phone,
                          job: user.job,
                          role_id: user.role_id,
                          token: 'Bearer ' + token,
                          role: user._doc.role
                        }
                      })
                    });
                  })
              } else {
                user._doc.role = { menus: [] }
                // 返回登陆成功信息(包含user)
                res.send({ status: 0, data: user })
              }
            } else {
              return res.json({
                status: 400,
                msg: '密码错误'
              })
            }
          })
      }
    })
})

//更新用户
router.put('/user/update', passport.authenticate('jwt', { session: false }), (req, res) => {
  const userData = req.body
  User.findByIdAndUpdate(
    { _id: userData.id },
    { $set: userData },
    { new: true }
  ).then(newUser => {
    res.json({
      status: 200,
      data: newUser,
      msg: '更新用户信息成功'
    })
  }).catch(err => {
    console.log(err)
    res.json({
      status: 400,
      msg: '更新用户异常，请稍后重试'
    })
  })
})

//删除用户
router.delete('/user/delete', passport.authenticate('jwt', { session: false }), (req, res) => {
  const userId = req.query.userId
  console.log(userId)
  User.findByIdAndDelete({ _id: userId })
    .then(doc => {
      res.json({
        status: 200,
        msg: '删除用户成功'
      })
    }).catch(err => {
      res.json({
        status: 400,
        msg: '删除用户出错了，请稍后再试'
      })
    })
})

//获取所有用户列表
router.get('/user/list', passport.authenticate('jwt', { session: false }), (req, res) => {
  const {
    pageNum,
    pageSize
  } = req.query
  User.find().then(users => {
    res.json({
      status: 200,
      data: pageFilter(users, pageNum, pageSize),
      msg: '查找所有用户列表成功'
    })
  }).catch(error => {
    console.error('获取用户列表异常', error)
    res.send({ status: 400, msg: '获取用户列表异常, 请重新尝试' })
  })
})

/**
 * 测试接口
 */
router.get("/user/current", passport.authenticate('jwt', { session: false }), (req, res) => {
  res.json({
    id: req.user.id,
    username: req.user.username,
    email: req.user.email,
    phone: req.user.phone,
    job: req.user.job,
  })
})

/*
得到指定数组的分页信息对象
 */
function pageFilter (arr, pageNum, pageSize) {
  pageNum = pageNum * 1
  pageSize = pageSize * 1
  const total = arr.length
  const pages = Math.floor((total + pageSize - 1) / pageSize)
  const start = pageSize * (pageNum - 1)
  const end = start + pageSize <= total ? start + pageSize : total
  const list = []
  for (var i = start; i < end; i++) {
    list.push(arr[i])
  }

  return {
    pageNum,
    total,
    pages,
    pageSize,
    list
  }
}

//暴露
module.exports = router